package com.dff.jrfw.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.dff.jrfw.R;
import com.dff.jrfw.remote.CustomCallBack;
import com.dff.jrfw.remote.RetrofitUtils;
import com.dff.jrfw.requestBody.QrCodeDto;
import com.dff.jrfw.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

public class ScanLoginDialog extends Dialog {

    private QrCodeDto qrCodeDto;

    public ScanLoginDialog(@NonNull Context context, QrCodeDto qrCodeDto) {
        super(context, R.style.CustomDialog);
        this.qrCodeDto = qrCodeDto;
        setCanceledOnTouchOutside(false);   // 点击其他地方dialog不消失
        setCancelable(false);         // 点击返回键dialog不消失
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scan_login_dialog);
        findViewById(R.id.cancle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                qrCodeDto.setStatus(2);
                doLogin();
            }
        });
        findViewById(R.id.confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                qrCodeDto.setStatus(3);
                doLogin();
            }
        });
    }

    private void doLogin(){
        RetrofitUtils.getService().qrCodeLogin("1","1",qrCodeDto).enqueue(new CustomCallBack<ResponseBody>() {

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.body() != null) {
                        String result = response.body().string();
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        if (code == 200) {
                            ToastUtil.toast("操作成功");
                        } else {
                            String msg = jsonObject.getString("msg");
                            ToastUtil.toast(msg);
                        }
                    } else {
                        ResponseBody errorResponseBody = response.errorBody();
                        if (errorResponseBody != null) {
                            ToastUtil.toast(errorResponseBody.string());
                        }
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
